clc; clearvars; close all;
addpath('CEC2010\')
addpath('CEC2010\datafiles\');
addpath('CEC2010\javarandom\bin\');
addpath('CEC2010\javarandom\src\');
global initial_flag
funcNum = 4;
initial_flag = 0;

k = 0;
NP = 3;     % 种群数
N = 1000;   %变量维度
maxIteration = 1;
dim = 1;
evaluations = 5 * 10 ^ 6;
evaluation = 0;
lowk = 10;  % k的上下界的设置
upk = log(1 - 0.8) / log(1 - 2 / N);
groupInfor = cell(1,N);
for i0 = 1 : N
    groupInfor{i0}(1,1) = i0;
end
upperBound = [100, 5, 32, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 5, 32, 100, 100, 100, 100];
lowerBound = [-100, -5, -32, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -5, -32, -100, -100, -100, -100];

while ~(size(groupInfor, 2) == 1 || (k > lowk && size(groupInfor, 2) == N) || k > upk || evaluation > 0.3 * evaluations)
    pi = randperm(1000);
    k = k + 1;
    lastIndex = 0;
    [pop, y, best] = initializeCC(NP, N, upperBound(funcNum), lowerBound(funcNum), @(x)benchmark_func(x, funcNum));
    evaluation = evaluation + 3;
    for i = 1 : N
        if lastIndex ~= 0
            G1 = groupFind(groupInfor, pi(i));
            G2 = groupFind(groupInfor, lastIndex);
        end
        if i == 1 || (G1 ~= G2)
            index1 = pi(i);
            subX = pop(:, index1);
            [subX, subY] = JADE(subX, y, best, index1, maxIteration, dim, lowerBound(funcNum), upperBound(funcNum), @(x)benchmark_func(x, funcNum));
            evaluation = evaluation + 3;
            [~, ind1] = min(subY);
            xi1 = subX(ind1, :);
            ind2 = randi(3);
            while ind1 == ind2
                ind2 = randi(3);
            end
            xi2 = subX(ind2, :);

            if lastIndex ~= 0
                x1 = best;
                x1(1, lastIndex) = xlasti1;     % x
                x1(1, pi(i)) = xi1;
                x2 = best;
                x2(1, lastIndex) = xlasti2;     % x`
                x2(1, pi(i)) = xi1;
                fx1 = benchmark_func(x1, funcNum);
                fx2 = benchmark_func(x2, funcNum);
                a = fx1 > fx2;
                evaluation = evaluation + 2;
                if(fx1 > fx2)
                    g1 = groupInfor{G1};
                    g2 = groupInfor{G2};
                    g1 = [g1, g2];
                    groupInfor{G1} = g1;
                    groupInfor(G2) = [];
                end
            end
            xlasti1 = xi1;
            xlasti2 = xi2;
            lastIndex = pi(i);
        end
    end
    disp(evaluation);
end
disp(groupInfor);
save('groupInfor.mat', 'groupInfor');
disp(evaluation);
save('evaluation.mat', 'evaluation');